#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    // void recursion(TreeNode* root,int& node_num)
    // {
    //     if(root==nullptr)
    //     {
    //         return;
    //     }
    //     node_num++;
    //     if(root->left)
    //     {
    //         recursion(root->left,node_num);
    //     }
    //     if(root->right)
    //     {
    //         recursion(root->right,node_num);
    //     }
    // }
    // int countNodes(TreeNode *root)
    // {
    //     int node_num = 0;
    //     if (root == nullptr)
    //     {
    //         return node_num;
    //     }
    //     recursion(root,node_num);
    //     return node_num;
    // }

    int recursion(TreeNode *root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        TreeNode *left_node = root->left;
        TreeNode *right_node = root->right;
        int left_depth = 0;
        int right_depth = 0;
        while (left_node)
        {
            left_node = left_node->left;
            left_depth++;
        }
        while (right_node)
        {
            right_node = right_node->right;
            right_depth++;
        }
        if (left_depth == right_depth)
        {
            return (2<<left_depth) - 1;
        }
        int leftnum = recursion(root->left);
        int rightnum = recursion(root->right);
        return leftnum + rightnum + 1;
    }

    int countNodes(TreeNode *root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        return recursion(root);
    }
};

int main()
{
    TreeNode *root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    root->right->left = new TreeNode(6);
    Solution sol;
    cout << sol.countNodes(root) << endl;
    return 0;
}